package com.classic.base;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * 懒加载工具类
 */
public abstract class LazyLoadFragment extends BaseFragment {

    protected boolean isViewInitiated;//判断视图是否初始化
    protected boolean isVisibleToUser;//用户是否可见
    protected boolean isDataInitiated;//数据是否初始化


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    //在所有生命周期函数之前调用，查看是否可见
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    //定义一个抽象函数，在子类中实现，作用就是加载初始化数据
    public abstract void fetchData();

    //准备加载数据，这里不是强制刷新
    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    //用户强制刷新的话，就应该是用户主动进行刷新了，当然也要去取数据了，用户第一嘛
    public boolean prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            fetchData();
            isDataInitiated = true;
            return true;
        }
        return false;
    }

    /**
     * @param view 要设置高度的View
     * @param high 高度
     */
    protected void setViewHigh(View view, int high) {
        ViewGroup.LayoutParams para = view.getLayoutParams();
        para.height = high;
        para.width = ViewGroup.LayoutParams.MATCH_PARENT;
        view.setLayoutParams(para);
    }

    protected int height;
    /**
     * 这个方法仅供 WeatherFragment使用
     * 设置标题栏目高度
     */
    protected void setBarHigh() {
//        Display display = getActivity().getWindowManager().getDefaultDisplay();
//        height = display.getHeight();
//        setViewHigh(rootView.findViewById(R.id.fl_layout), (display.getHeight() - DisplayUtils.dp2px(getContext(), 52) - getStatusBarHeight(getContext())));
//        setViewHigh(rootView.findViewById(R.id.tv_titlebar), DisplayUtils.dp2px(getContext(), 52) + getStatusBarHeight(getContext()));
    }

    protected void setText(TextView v, Object t) {
        if (null != v) {
            v.setText(String.valueOf(t));
        }
    }

    protected void setText(int v, String t) {
        TextView viewById = rootView.findViewById(v);
        if (null != viewById) {
            viewById.setText(t);
        }
    }
}